<template>
  <div>
    <h1>分类列表</h1>
  </div>
  <div>
    <el-button type="primary" @click="onAddRootType">添加</el-button>
  </div>
  <!-- 表格数据 -->
  <div>
    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      default-expand-all
    >
      <el-table-column prop="id" label="ID" sortable width="100px" />
      <el-table-column prop="name" label="类型名称" sortable width="120px" />
      <el-table-column prop="parentId" label="上级ID" sortable width="120px" />
      <el-table-column prop="typeImage" label="类型图片" sortable width="150px">
        <template #default="scope">
          <el-image
            :src="scope.row.typeImage"
            v-if="scope.row.typeImage != null ? scope.row.typeImage : null"
            style="width: 50px; height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="typeTop" label="排序" sortable width="100px" />
      <el-table-column prop="typeStatus" label="状态" sortable width="120px">
        <template #default="scope">
          <span v-if="scope.row.typeStatus == 0">显示</span>
          <span v-if="scope.row.typeStatus == 1">隐藏</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" sortable>
        <template #default="scope">
          <el-button type="primary" size="small" @click="onAddType(scope.row)"
            >添加</el-button
          >
          <el-button type="primary" size="small" @click="onEditType(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="onDeleteType(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 添加类型 -->
  <div>
    <el-dialog v-model="dialogFormVisible" title="添加类型" width="500">
      <el-form :model="form" ref="ruleFormRef" :rules="rules">
        <el-form-item
          label="分类名称"
          :label-width="formLabelWidth"
          prop="typeName"
        >
          <el-input v-model="form.typeName" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="分类图片"
          :label-width="formLabelWidth"
          prop="typeImage"
        >
          <el-upload
            class="avatar-uploader"
            action="http://localhost:10010/shop/type/uploadImage"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :headers="headers"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth" prop="typeTop">
          <el-input v-model="form.typeTop" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="状态"
          :label-width="formLabelWidth"
          prop="typeStatus"
        >
          <el-radio-group v-model="form.typeStatus">
            <el-radio :value="0">显示</el-radio>
            <el-radio :value="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { getTreeList, addType } from "../api/api";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, type UploadProps } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const tableData = ref([]);

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const ruleFormRef = ref<FormInstance>();
const form = ref({
  typeImage: "",
  typeName: "",
  typeStatus: null,
  typePid: 0,
  typeTop: null,
});

const checkImage = (rule: any, value: any, callback: any) => {
  if (form.value.typePid != 0) {
    if (imageUrl.value == null || imageUrl.value == "") {
      return callback(new Error("请选择图片"));
    } else {
      return callback();
    }
  }else{
    return callback();
  }
};

const rules = ref({
  typeName: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  typeImage: [{ validator: checkImage, trigger: "blur" }],
  typeTop: [{ required: true, message: "请输入排序", trigger: "blur" }],
  typeStatus: [
    { required: true, message: "请输入分类状态", trigger: "change" },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onSumbitAddType();
    } else {
      console.log("error submit!", fields);
    }
  });
};

//确认添加
const onSumbitAddType = () => {
  form.value.typeImage = imageUrl.value;
  addType(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadTypeList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//上传图片
const imageUrl = ref("");
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  imageUrl.value = response.data;
};

//显示添加顶级分类
const onAddRootType = () => {
  console.log("onAddType");
  form.value = {
    typeImage: "",
    typeName: "",
    typeStatus: null,
    typePid: 0,
    typeTop: null,
  };
  imageUrl.value = null;
  dialogFormVisible.value = true;
};

//显示添加子级分类
const onAddType = (row: any) => {
  console.log("onAddType");
  form.value = {
    typeImage: "",
    typeName: "",
    typeStatus: null,
    typePid: row.id,
    typeTop: null,
  };
  imageUrl.value = null;
  dialogFormVisible.value = true;
};

const loadTypeList = () => {
  getTreeList().then((res) => {
    tableData.value = res.data.data;
  });
};

onMounted(() => {
  loadTypeList();
});
</script>

<!-- 上传图片样式 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
